<template>
  <el-dialog
    class="material-collection-comp"
    title="材料领用"
    :close-on-click-modal="false"
    :destroy-on-close="true"
    :visible="visible"
    :width="$setRem(980)"
    :before-close="handleCancel">
    <el-form
      element-loading-custom-class="custom-load"
      :model="ruleForm"
      :rules="rules"
      label-suffix="："
      size="medium"
      ref="ruleForm"
      :label-width="$setRem(140)"
      class="rule-form"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="领用人" prop="claimUser" required>
            <span class="detail-text" v-if="hasDetail">{{ ruleForm.claimUserName || '' }}</span>
            <el-select
              v-else
              placeholder="请选择领用人"
              filterable
              v-model="ruleForm.claimUser">
              <el-option
                v-for="v in userList"
                :label="v.userName"
                :value="v.uuid"
                :key="v.uuid">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="领用单位" prop="claimCompany" required>
            <span class="detail-text" v-if="hasDetail">{{ ruleForm.claimCompany || '' }}</span>
            <el-input
              v-else
              type="text"
              :disabled="!ruleForm.claimCompany"
              placeholder="领用单位"
              :value="ruleForm.claimCompany">
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="领用日期" prop="claimDate" required>
            <span class="detail-text" v-if="hasDetail">{{ ruleForm.claimDate || '' }}</span>
            <el-date-picker
              v-else
              v-model="ruleForm.claimDate"
              format="yyyy-MM-d"
              value-format="yyyy-MM-dd"
              type="date"
              placeholder="请选择领用日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="抄送人员" prop="copyUser">
            <span class="detail-text" v-if="hasDetail">{{ ruleForm.copyUserName || '' }}</span>
            <el-select
              v-else
              placeholder="请选择抄送人员"
              :multiple="false"
              clearable
              filterable
              v-model="ruleForm.copyUser">
              <el-option
                v-for="v in userList"
                :label="v.userName"
                :value="v.uuid"
                :key="v.uuid">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row class="annex">
        <el-col :span="12">
          <el-form-item label="附件" prop="annexUrl" required>
            <div v-if="ruleForm.annexUrl || hasDetail" class="image-list">
              <div v-if="!hasDetail" class="mask">
                <i class="el-icon-delete" @click="handleRemovePic"></i>
              </div>
              <img :src="$checkUrl(ruleForm.annexUrl)" class="avatar" />
            </div>
            <el-upload
              v-else
              class="avatar-uploader"
              action="#"
              accept=".jpg,.png,.jpeg"
              :show-file-list="false"
              :auto-upload="false"
              :on-change="beforeAvatarUpload">
              <i v-if="annexUrlLoading" class="el-icon-loading avatar-loading-icon"></i>
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <div class="btns" v-if="!hasDetail">
      <el-button
        class="add-btn"
        @click="handleAdd"
        type="primary"
        size="small"
        icon="el-icon-plus">新增</el-button>
      <el-button
        class="add-btn"
        @click="handleDelete"
        type="danger"
        size="small"
        icon="el-icon-delete">删除</el-button>
    </div>
    <el-table
      class="table-container"
      :data="tableData"
      element-loading-custom-class="custom-load"
      @selection-change="handleSelectionChange"
      row-key="id">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column label="序号" type="index" width="60" align="center"></el-table-column>
      <el-table-column label="材料名称" prop="materialTypeName" align="center"></el-table-column>
      <el-table-column label="规格/型号" prop="model" align="center"></el-table-column>
      <el-table-column label="领用数量" prop="claimNum" width="100" align="center"></el-table-column>
      <el-table-column label="剩余库存" prop="currentNum" align="center"></el-table-column>
      <el-table-column label="单位" prop="unit" align="center"></el-table-column>
      <div class="empty-content" slot="empty">
        <i class="iconfont iconwushuju"></i>
        <p>暂无数据</p>
      </div>
    </el-table>
    <add-itive
      :visible="addVisible"
      @cancel="addVisible = false"
      @submit="handleSubmit">
    </add-itive>
    <span slot="footer" class="dialog-footer">
      <el-button
        v-if="!hasDetail"
        size="medium"
        type="primary"
        :loading="loading"
        @click="hanldeSave">
        确 认
      </el-button>
      <el-button size="medium" @click="handleCancel">取 消</el-button>
    </span>
  </el-dialog>
</template>

<script>
import addItive from '@/components/project/material/addItive';

export default {
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    type: {
      type: String,
      default: 'add'
    },
    options: {
      type: Object,
      default: () => ({})
    },
    loading: {
      type: Boolean,
      default: false
    },
  },
  data() {
    return {
      userList: [],
      tableData: [],
      multipleSelection: [],
      picLoading: false,
      addVisible: false,
      annexUrlLoading: false,
      ruleForm: {
        id: '',
        claimUser: '',
        claimUserName: '',
        claimCompany: '',
        annexUrl: '',
        copyUser: '',
        copyUserName: '',
        claimDate: this.$moment().format('YYYY-MM-DD')
      },
      rules: {
        claimUser: [
          { required: true, message: '请选择领用人' },
        ],
        claimCompany: [
          { required: true, message: '领用单位不能为空' },
        ],
        annexUrl: [
          { required: true, message: '请上传附件' },
        ],
        claimDate: [
          { required: true, message: '请选择时间' },
        ],
      },
    };
  },
  computed: {
    // 新增
    hasAdd() {
      return this.type === 'add';
    },
    // 编辑
    hasEdit() {
      return this.type === 'edit';
    },
    hasDetail() {
      return this.type === 'detail';
    },
    // 当前抄送人信息
    currentCopyUser() {
      return this.userList.find(v => (
        v.uuid === this.ruleForm.copyUser
      )) || {};
    },
    // 当前领用人信息
    currentClaimUserUser() {
      return this.userList.find(v => (
        v.uuid === this.ruleForm.claimUser
      )) || {};
    },
  },
  watch: {
    options: {
      deep: true,
      handler(data) {
        const keys = Object.keys(this.ruleForm);
        data && Object.keys(data).length && keys.forEach(key => {
          this.ruleForm[key] = data[key] || '';
        });
        this.tableData = data.materialOutRecords || [];
      }
    },
    visible(value) {
      if (!value) {
        Object.keys(this.ruleForm).forEach(key => {
          this.ruleForm[key] = key === 'claimDate'
            ? this.$moment().format('YYYY-MM-DD')
            : '';
        });
        this.multipleSelection = [];
        this.tableData = [];
      }
    },
    'ruleForm.claimUser'(val) {
      if (val) {
        const current = this.userList.find(v => v.uuid === val);
        if (current) {
          this.ruleForm.claimUserName = current.userName;
          this.ruleForm.claimCompany = current.organizationName;
        }
      }
    },
    'ruleForm.copyUser'(val) {
      if (val) {
        const current = this.userList.find(v => v.uuid === val);
        if (current) this.ruleForm.copyUserName = current.userName;
      }
    },
  },
  created() {
    this.getUserList();
  },
  components: {
    addItive
  },
  methods: {
    /**
     * 获取用户列表数据
     */
    async getUserList() {
      const params = {
        pageFlag: false
      };
      const { success, data: {
        data
      }} = await this.$Model.getUserList(params);
      if (success && data) {
        this.userList = data.list || [];
      }
    },
    // 新增材料
    handleAdd() {
      this.addVisible = true;
    },
    // 删除材料
    handleDelete() {
      this.tableData = this.tableData.filter(item => {
        return !this.multipleSelection.some(v => v.id === item.id);
      });
    },
    // 上传图片
    async beforeAvatarUpload(file) {
      const fm = new FormData();
      fm.append('file', file.raw);
      this.picLoading = true;
      const { success, data: { data }} = await this.$Model.fileUpload(fm);
      this.picLoading = false;
      if (success) {
        this.ruleForm.annexUrl = data;
      }
    },
    // 删除图片
    async handleRemovePic(file) {
      if (!this.ruleForm.annexUrl) return;
      this.ruleForm.annexUrl = '';
      const params = {
        filePath: this.ruleForm.annexUrl
      };
      this.$Model.fileDelete(params, { showErr: false });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 确认添加材料
    handleSubmit(data) {
      this.tableData = data.filter(item => item.claimNum);
      this.addVisible = false;
    },
    handleCancel() {
      this.$emit('cancel');
    },
    hanldeSave() {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          this.$emit('submit', {
            ...this.ruleForm,
            materialOutRecords: this.tableData
          });
        }
      });
    }
  }
};
</script>

<style scoped lang="scss">
  @import "../../../assets/styles/table";
  @import "../../../assets/styles/dialog";

  .material-collection-comp {
    .btns {
      margin: 10px 0;
      width: 100%;
      text-align: right;
    }
    /deep/ .el-form-item__content {
      min-width: 240px;
      max-width: 400px;
    }
    .table-container {
      margin: 20px 0;
      width: 100%;
      /deep/ .el-table__body-wrapper {
        min-height: 200px;
        max-height: 350px;
        overflow-y: auto;
        .file-text {
          max-width: 150px;
          display: flex;
          align-items: center;
          justify-content: flex-start;
          padding-right: 20px;
          .file-name {
            max-width: 130px;
            display: inline-block;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            position: relative;
          }
          .img {
            width: 100px;
            height: 65px;
          }
          i.file-delete {
            font-size: 16px;
            color: $mainColor;
            cursor: pointer;
          }
        }
      }
    }
    .file-disable {
      /deep/ .el-upload {
        .el-button {
          span {
            color: #fff;
          }
        }
      }
    }
    .avatar-uploader {
      .el-upload {
        position: relative;
      }
    }
    .image-list {
      width: 100%;
      height: 100%;
      position: relative;
      transition: all .3s;
      .mask {
        position: absolute;
        width: 100%;
        height: 100%;
        left: 0;
        top: 0;
        cursor: pointer;
        text-align: center;
        color: #fff;
        opacity: 0;
        font-size: 20px;
        background-color: rgba(0,0,0,.5);
        transition: opacity .3s;
        &:hover {
          opacity: 1;
        }
      }
      .avatar {
        width: 100%;
        height: 100%;
      }
      .el-icon-delete {
        position: absolute;
        top: calc(50% - 10px);
        left: calc(50% - 10px);
      }
    }
    .avatar-loading-icon {
      font-size: 28px;
      color: #8c939d;
      width: 100px;
      height: 100px;
      line-height: 100px;
      text-align: center;
      border-radius: 6px;
      &:hover {
        color: $mainColor;
      }
    }
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 100px;
      height: 100px;
      line-height: 100px;
      text-align: center;
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      &:hover {
        border-color: $mainColor;
        color: $mainColor;
      }
    }
    .detail-text {
      color: $mainColor;
    }
    .annex {
      /deep/ .el-form-item__content {
        .image-list {
          width: 120px;
        }
      }
    }
  }
</style>
